package com.woshua.fixedmodel;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.woshua.fixedmodel.testutils.FixDexUtils;
import com.woshua.fixedmodel.testutils.MyConstant;
import com.woshua.fixedmodel.testutils.TestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void testClick(View view) {
        TestUtils testUtils=new TestUtils();
        testUtils.test();
    }

    public void fixClick(View view) {
        fixBug();
    }

    private void fixBug() {
        File fileDir=this.getDir(MyConstant.DEX_DIR,MODE_PRIVATE);
        String name="classes2.dex";

        String filePath=fileDir.getAbsolutePath()+File.separator+name;

        File file=new File(filePath);

        if(file.exists())
        {
            Log.i("info","dex exists");
            file.delete();
        }

        InputStream is=null;
        FileOutputStream os=null;

        try {
            is=new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+name);
            os=new FileOutputStream(filePath);

            int len=0;
            byte[] buffer=new byte[1024];

            while ((len=is.read(buffer))!=-1)
            {
                os.write(buffer,0,len);
            }

            File f=new File(filePath);

            if(f.exists())
            {
                Toast.makeText(this,"dex overflow",Toast.LENGTH_SHORT).show();
            }

            if (FixDexUtils.isGoingToFix(this)) {
                FixDexUtils.loadFixDex(this);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
